﻿using AutoMapper;
using IceZero.Business.Models;
using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace IceZero.RootNode.Helpers
{
    /// <summary>
    /// Mapper 帮助器
    /// </summary>
    public class AutoMapperHelper
    {
        /// <summary>
        /// 默认映射器
        /// </summary>
        public static IMapper DefaultMapper { get; set; }

        /// <summary>
        /// 配置对象
        /// </summary>
        public static IConfigurationProvider Configuration { get; set; }

        /// <summary>
        /// 构建配置对象和默认映射器
        /// </summary>
        /// <returns></returns>
        public static IConfigurationProvider Configure()
        {
            var types = AppDomain.CurrentDomain.GetAssemblies().ToList();
            var assemblyFiles = Directory.GetFiles(AppContext.BaseDirectory, "*.Business.Models.dll").ToList();
            //获取程序启动时所有程序集
            var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
            // 加载所有DataStore.Models 结尾的程序集
            assemblyFiles.ForEach(assemblyFile =>
            {
                var file = new FileInfo(assemblyFile);
                var fileName = Path.GetFileNameWithoutExtension(file.Name);
                var isExist = assemblies.Exists(assembly =>
                {
                    var existFileName = assembly.GetName().Name;
                    return existFileName == fileName;
                });
                //只加载还不存在的数据集
                if (!isExist)
                {
                    Assembly.LoadFile(assemblyFile);
                }
            });
            //重新加载程序集列表
            assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
            var assemblyNames = assemblies.Where(a => a.GetName().Name.EndsWith(".Business.Models")).ToList();
            Configuration = new MapperConfiguration(config =>
            {
                config.AddMaps(assemblyNames);
            });
#if DEBUG
            // only during development, validate your mappings; remove it before release
            Configuration.AssertConfigurationIsValid();
#endif
            DefaultMapper = Configuration.CreateMapper();
            return Configuration;
        }
    }
}
